package com.base.cn.platform.os.controller.agent.settlement;

import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.agent.income.AgentIncome;
import com.base.cn.platform.os.entity.agent.income.AgentIncomeInfo;
import com.base.cn.platform.os.entity.agent.settlement.AgentSettlement;
import com.base.cn.platform.os.entity.agent.user.AgentUser;
import com.base.cn.platform.os.service.agent.income.AgentIncomeInfoBiz;
import com.base.cn.platform.os.service.agent.settlement.AgentSettlementBiz;
import com.base.cn.platform.os.service.agent.user.AgentUserBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 推广员结算记录Controller
 *
 * @author LIZHIPENG
 * @create 2018-05-14 下午 6:02
 */
@RestController
@RequestMapping("/course")
public class AgentSettlementController extends BaseController {

    @Autowired
    private AgentUserBiz agentUserBiz;
    @Autowired
    private AgentIncomeInfoBiz agentIncomeInfoBiz;
    @Autowired
    private AgentSettlementBiz agentSettlementBiz;

    /**
     * 查询结算列表(分页)
     * @param currentPage 页码
     * @param agentSettlement 条件
     * @param agentUserData 是否设置推广员数据（true：是，false：否）
     * @return
     */
    @RequestMapping("/querySettlementListPage")
    public PageInfo<AgentSettlement> querySettlementListPage(@RequestParam(value = "currentPage", required = false, defaultValue = "1") int currentPage,
                                                             @RequestBody AgentSettlement agentSettlement,
                                                             @RequestParam("agentUserData") boolean agentUserData){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        return agentSettlementBiz.querySettlementListPage(page, agentSettlement, agentUserData);
    }

    /**
     * 根据ID查询结算
     * @param agentSettlementId 结算ID
     * @param agentUserData 是否设置推广员数据（true：是，false：否）
     * @return
     */
    @RequestMapping("/findSettlementById")
    public AgentSettlement findSettlementById(@RequestParam("agentSettlementId")BigDecimal agentSettlementId,
                                              @RequestParam("agentUserData") boolean agentUserData){
        return agentSettlementBiz.findSettlementById(agentSettlementId, agentUserData);
    }

    /**
     * 前台用户确认结算
     * @param agentSettlement 结算条件
     * @param userId 用户ID
     * @return Map<String, Object>
     */
    @RequestMapping("/confirmSettlement")
    public Map<String, Object> confirmSettlement(@RequestBody AgentSettlement agentSettlement,
                                                @RequestParam("userId") BigDecimal userId){

            //查询推广员身份
            AgentUser agentUser = agentUserBiz.findAgentUserByUserId(userId, true, false, false);
            if(ObjectUtils.isEmpty(agentUser)){
                return ResultUtil.ERROR();
            }
            if(agentUser.getStatus() != 3){
                return ResultUtil.ERROR("您的推广员身份状态异常");
            }
            //查询可结算收益
            Map<String, Object> map = agentIncomeInfoBiz.queryIsAvailableIncome(agentUser);
            if(ObjectUtils.isEmpty(map)){
                return ResultUtil.ERROR("您还没有收益可以结算");
            }
            List<AgentIncomeInfo> incomeInfoList = (List<AgentIncomeInfo>)map.get("incomeInfos");
            if(ObjectUtils.isEmpty(incomeInfoList)){
                return ResultUtil.ERROR("您还没有收益可以结算");
            }

            //结算集合
            List<AgentSettlement> settlementList = new ArrayList<>();

            AgentIncome agentIncome = agentUser.getAgentIncome();
            Calendar calendar = Calendar.getInstance();
            if(agentUser.getSettType() == 2){//月结
                //通过年月进行分组
                Map<String,List<AgentIncomeInfo>> agentIncomeInfoListMap = incomeInfoList.stream().collect(Collectors.groupingBy(e->DateUtils.format(e.getCreateTime(),"yyyy-MM")));
                TreeMap<String,List<AgentIncomeInfo>> agentIncomeInfoListTreeMap = new TreeMap<>();
                agentIncomeInfoListMap.forEach((k,v)->{
                    agentIncomeInfoListTreeMap.put(k,v);
                });
                agentIncomeInfoListTreeMap.forEach((k,v)->{
                    AgentSettlement settlement = new AgentSettlement();
                    settlement.setAgentUserId(agentUser.getId());
                    settlement.setSettType(agentUser.getSettType());
                    settlement.setCycleNum( agentIncome.getCycleNum() + 1 );//结算周期
                    settlement.setStartTime(DateUtils.parseDate(k+"-01 00:00:00","yyyy-MM-dd HH:mm:ss"));
                    calendar.setTime(settlement.getStartTime());
                    calendar.add(Calendar.MONTH,1);
                    settlement.setEndTime(calendar.getTime());
                    //计算收益
                    method1(v,settlement);
                    settlement.setSettlementFrom(agentSettlement.getSettlementFrom());
                    settlement.setStatus(2);
                    settlementList.add(settlement);
                    agentIncome.setCycleNum(agentIncome.getCycleNum() +1);
                });
            }else if(agentUser.getSettType() == 3){//年结
                Map<String,List<AgentIncomeInfo>> yearListMap = incomeInfoList.stream().collect(Collectors.groupingBy(e->DateUtils.format(e.getCreateTime(),"yyyy")));
                TreeMap<String,List<AgentIncomeInfo>> yearListTreeMap = new TreeMap<>();
                yearListMap.forEach((k,v)->{
                    yearListTreeMap.put(k,v);
                });
                yearListTreeMap.forEach((k,v)->{
                    AgentSettlement settlement = new AgentSettlement();
                    settlement.setAgentUserId(agentUser.getId());
                    settlement.setSettType(agentUser.getSettType());
                    settlement.setCycleNum(agentIncome.getCycleNum() +1);//结算周期

                    method1(v, settlement);

                    settlement.setStartTime(DateUtils.parseDate(k+"-01-01 00:00:00","yyyy-MM-dd HH:mm:ss"));
                    calendar.setTime(settlement.getStartTime());
                    calendar.add(Calendar.YEAR,1);
                    settlement.setEndTime(calendar.getTime());
                    settlement.setSettlementFrom(agentSettlement.getSettlementFrom());
                    settlement.setStatus(2);
                    settlementList.add(settlement);
                    agentIncome.setCycleNum(agentIncome.getCycleNum() + 1);
                });
            }else if(agentUser.getSettType() == 1){//随时结
                AgentSettlement settlement = new AgentSettlement();
                settlement.setAgentUserId(agentUser.getId());
                settlement.setSettType(agentUser.getSettType());
                settlement.setCycleNum(agentIncome.getCycleNum() +1);//结算周期
                //计算收益
                method1(incomeInfoList, settlement);
                settlement.setStartTime(new Date());
                settlement.setEndTime(new Date());
                settlement.setSettlementFrom(agentSettlement.getSettlementFrom());
                settlement.setStatus(2);
                settlementList.add(settlement);
                agentIncome.setCycleNum(agentIncome.getCycleNum() + 1);
            }
            agentSettlementBiz.confirmSettlement(agentUser,settlementList, incomeInfoList, agentIncome);
            StringBuilder   cycleNum = new StringBuilder();
            Double amount  = 0.0;
            if(settlementList.size()>1){
                cycleNum.append(settlementList.get(0).getCycleNum()).append("~").append(settlementList.get(settlementList.size()-1).getCycleNum());
            }else{
                cycleNum.append(settlementList.get(0).getCycleNum());
            }
            for(AgentSettlement settlement:settlementList){
                amount+=settlement.getBalancePrice();
            }
        HashMap<String, Object> result = new HashMap<>();
        result.put("cycleNum",cycleNum);
        result.put("amount",amount);
        Map<String,Object> resultMap = ResultUtil.SUCCESS("结算成功", result);
        return resultMap;
    }

    /**
     * 后台确认结算
     * @return Map<String, Object>
     */
    /*@RequestMapping("/updateSettlement")
    public Map<String, Object> updateSettlement(HttpServletRequest request,
                                                @RequestBody AgentSettlement agentSettlement) throws Exception {
        if(ObjectUtils.isEmpty(agentSettlement) || !DataUtil.idIsNotNull(agentSettlement.getId())){
            return ResultUtil.ERROR();
        }
        AgentSettlement settlement = agentSettlementBiz.findSettlementById(agentSettlement.getId(),false);
        if(settlement==null){
            return ResultUtil.ERROR("结算记录不存在");
        }
        AgentAccount agentAccount = new AgentAccount();
        agentAccount.setAgentUserId(settlement.getAgentUserId());
        List<AgentAccount> accountList = null;
        AgentAccount account = null;
        PayService payService = null;
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.PAY);
        Map<String,Object> resultMap = null;
        Map<String,String> paramsData = new HashMap<>();
        if(settlement.getAccountType().intValue()==1){//微信
            agentAccount.setAccountType(1);
            accountList = accountBiz.findAgentAccount(agentAccount);
            if(ObjectUtils.isEmpty(accountList)){
                return ResultUtil.ERROR("未绑定微信信息");
            }
            account = accountList.get(0);
            //String openId = "ol5KIjov_ynbuKT43ls9Pl2CQiQU";
            payService = new WeiXinUtils();
            paramsData.put("openId",account.getAccount());
            paramsData.put("amount",String.valueOf(settlement.getBalancePrice()));
            //paramsData.put("amount","0.5");
            paramsData.put("desc","推广收益结算");
        }else if(settlement.getAccountType().intValue()==2){//支付宝
            agentAccount.setAccountType(2);
            accountList = accountBiz.findAgentAccount(agentAccount);
            if(ObjectUtils.isEmpty(accountList)){
                return ResultUtil.ERROR("未支付宝账号");
            }
            TreeMap<String,String> infoMap = sysConfigService.getSysConfigContext(ConfigName.INFO);
            account = accountList.get(0);
            payService = new AlipayUtils();
            paramsData.put("account",account.getAccount());//收款方账户
            paramsData.put("amount",String.valueOf(settlement.getBalancePrice()));//转账金额 单位：元
            paramsData.put("payerShowName",infoMap.get("company"));//付款方姓名
            paramsData.put("realName",account.getRealName()); //收款方真实姓名
            paramsData.put("remark","推广收益结算"); //转账备注
        }
        resultMap = payService.payTransfer(request,configMap,paramsData);
        if(resultMap != null && ResultUtil.getSuccess(resultMap)){
            settlement.setStatus(2);
            String thirdOrderNot = (String)resultMap.get("paymentNo");
            settlement.setThirdOrderNo(thirdOrderNot);
            agentSettlementBiz.addOrUpdateSettlement(settlement);
            return ResultUtil.SUCCESS("保存成功");
        }else{
            return resultMap;
        }
    }*/

    //前台用户申请结算方法抽取
    private void method1(List<AgentIncomeInfo> incomeInfos, AgentSettlement settlement){
        double balancePrice;//结算金额
        double spreadPrice=0;//推广金额
        double rewardPrice=0;//奖励金额
        for (AgentIncomeInfo info : incomeInfos) {
            spreadPrice += info.getIncomePrice()==null?0D:info.getIncomePrice();//推广金额和
            rewardPrice += info.getBonusPrice()==null?0D:info.getBonusPrice();//奖励金额和
            info.setStatus(2);
        }
        balancePrice = spreadPrice + rewardPrice;
        settlement.setBalancePrice(balancePrice);
        settlement.setSpreadPrice(spreadPrice);
        settlement.setRewardPrice(rewardPrice);
    }
}
